Synchronized Block
Instead of synchronizing an entire method, we can synchronize only the critical section.
This is called the critical section. Only one thread can execute this block at a time for the same object.
class Counter {
int count = 0;
void increment() {
synchronized (this) {
count++;
}
}
}
public class SynchroThreadBlockDemo {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final count: " + counter.count);
}
}